<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const times = 20000;
      let html = "";
      for (let i = 0; i < times; i++) {
        html = `<div>${i}${html}</div>`;
      }
      document.body.innerHTML += html;

      let queue = []; //  创建缓存样式的数组
      let microTask; // 执行修改样式的微任务
      const st = () => {
        console.log("任务队列的数量", queue.length); // 20000
        const div = document.querySelector("div");
        // 合并样式
        const style = queue.reduce((acc, cur) => ({ ...acc, ...cur }), {});
        console.log({ style });
        // color: "red"
        // fontSize: "19px";
        // margin: "19px";
        for (let prop in style) {
          div.style[prop] = style[prop];
        }
        queue = [];
        microTask = null;
      };
      const setStyle = (style) => {
        queue.push(style);
        // 创建微任务 当同步的循环执行完以后 异步开始执行
        if (!microTask) microTask = Promise.resolve().then(st);
      };
      for (let i = 0; i < times; i++) {
        const style = {
          fontSize: (i % 12) + 12 + "px",
          color: i % 2 ? "red" : "green",
          margin: (i % 12) + 12 + "px",
        };
        setStyle(style);
      }
    </script>
  </body>
</html>
